import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { varRouter } from '@/router'
// console.log(store.getters.token)
const whiteList = ['/login', '/404'] // 定义白名单  所有不受权限控制的页面
router.beforeEach(async(to, form, next) => {
  NProgress.start() // 开启进度条
  if (store.getters.token) {
    // 有token
    // 获取用户资料
    if (!store.getters.userInfo.id) {
      const res = await store.dispatch('user/getUserInfo')
      console.log(varRouter)
      console.log(res)
      const filterRouter = varRouter.filter(item => {
        return res.roles.menus.some(menu => menu === item.name)
      })
      console.log(filterRouter)
      router.addRoutes(
        [...filterRouter,
          { path: '*', redirect: '/404', hidden: true }]
      )
      store.commit('user/setmenus', filterRouter)
      next(to.path)
    }

    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 如果没有token
    if (whiteList.indexOf(to.path) > -1) {
      // 如果找到了 表示在在名单里面
      next()
    } else {
      next('/login') // 跳到登录页
    }
  }
  // next()
  NProgress.done()
})
// 后置守卫
router.afterEach(function() {
  NProgress.done() // 关闭进度条
})
